package com.aurora.oa.home.view;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aurora.oa.R;
import com.aurora.oa.home.adapter.ArticleAdapter;
import com.aurora.oa.home.adapter.ImageCarouseAdapter;
import com.aurora.oa.home.bean.ArticleBean;
import com.aurora.oa.home.bean.ImageCarouselBean;
import com.aurora.oa.customview.ItemDivider;
import com.aurora.oa.home.bean.MessageBean;
import com.aurora.oa.home.model.HomePageData;
import com.aurora.oa.home.presenter.HomeFragmentPresenter;
import com.aurora.oa.home.presenter.HomeFragmentPresenterImpl;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/3/8 0008.
 */
public class HomePageFragment extends Fragment implements HomeFragmentView{

    HomeFragmentPresenter homeFragmentPresenter;
    private static final String ARTICLE_LATEST_PARAM = "param";

    private static final int UPTATE_VIEWPAGER = 0;

    //轮播的最热新闻图片
    ViewPager vpHottest;
    //轮播图片下面的小圆点
    LinearLayout llHottestIndicator;
    LinearLayout ll_list_artical;
    RecyclerView rv_list_article;

    //存储的参数
    private String mParam;

    //获取 fragment 依赖的 Activity，方便使用 Context
    private Activity mAct;

    //设置当前 第几个图片 被选中
    private int autoCurrIndex = 0;

    private ImageView[] mBottomImages;//底部只是当前页面的小圆点

    private Timer timer = new Timer(); //为了方便取消定时轮播，将 Timer 设为全局

    //定时轮播图片，需要在主线程里面修改 UI
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPTATE_VIEWPAGER:
                    if (msg.arg1 != 0) {
                        vpHottest.setCurrentItem(msg.arg1);
                    } else {
                        //false 当从末页调到首页是，不显示翻页动画效果，
                        vpHottest.setCurrentItem(msg.arg1, false);
                    }
                    break;
            }
        }
    };
    private TextView tv_news_message;

    public static HomePageFragment newInstance(String param) {
        HomePageFragment fragment = new HomePageFragment();
        Bundle args = new Bundle();
        args.putString(ARTICLE_LATEST_PARAM, param);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            mParam = savedInstanceState.getString(ARTICLE_LATEST_PARAM);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        mAct = getActivity();
        homeFragmentPresenter = new HomeFragmentPresenterImpl(this);
        vpHottest =(ViewPager)view.findViewById(R.id.vp_hottest);
        llHottestIndicator =(LinearLayout) view.findViewById(R.id.ll_hottest_indicator);
        rv_list_article = (RecyclerView) view.findViewById(R.id.rv_list_article);
        tv_news_message = (TextView)view.findViewById(R.id.tv_news_message);
        ll_list_artical = (LinearLayout)view.findViewById(R.id.ll_list_artical);
        ll_list_artical.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mAct,ArticalListActivity.class));
            }
        });
        //替代findviewbyid,暂时不使用
        //ButterKnife.inject(this, view);
        return view;
    }

    /**
     * 在这里为界面填充数据或请求网络
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //请求数据并刷新界面
        homeFragmentPresenter.refreshHomeFragment();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //ButterKnife.reset(this);
    }


    /**
     * 初始化图片轮播控件
     * @param headerArticles
     */
    private void setUpViewPager(final List<ImageCarouselBean> headerArticles) {
        ImageCarouseAdapter imageAdapter = new ImageCarouseAdapter(mAct, headerArticles);
        vpHottest.setAdapter(imageAdapter);

        //创建底部指示位置的导航栏
        mBottomImages = new ImageView[headerArticles.size()];

        for (int i = 0; i < mBottomImages.length; i++) {
            ImageView imageView = new ImageView(mAct);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10, 10);
            params.setMargins(5, 0, 5, 0);
            imageView.setLayoutParams(params);
            if (i == 0) {
                imageView.setBackgroundResource(R.mipmap.indicator_select);
            } else {
                imageView.setBackgroundResource(R.mipmap.indicator_not_select);
            }

            mBottomImages[i] = imageView;
            //把指示作用的原点图片加入底部的视图中
            llHottestIndicator.addView(mBottomImages[i]);

        }

        vpHottest.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

                                              //图片左右滑动时候，将当前页的圆点图片设为选中状态
                                              @Override
                                              public void onPageSelected(int position) {
                                                  // 一定几个图片，几个圆点，但注意是从0开始的
                                                  int total = mBottomImages.length;
                                                  for (int j = 0; j < total; j++) {
                                                      if (j == position) {
                                                          mBottomImages[j].setBackgroundResource(R.mipmap.indicator_select);
                                                      } else {
                                                          mBottomImages[j].setBackgroundResource(R.mipmap.indicator_not_select);
                                                      }
                                                  }

                                                  //设置全局变量，currentIndex为选中图标的 index
                                                  autoCurrIndex = position;
                                              }

                                              @Override
                                              public void onPageScrolled(int i, float v, int i1) {
                                              }

                                              @Override
                                              public void onPageScrollStateChanged(int state) {
                                              }
                                          }
        );

        // 设置自动轮播图片，5s后执行，周期是5s
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = UPTATE_VIEWPAGER;
                if (autoCurrIndex == headerArticles.size() - 1) {
                    autoCurrIndex = -1;
                }
                message.arg1 = autoCurrIndex + 1;
                mHandler.sendMessage(message);
            }
        }, 5000, 5000);
    }

    /**
     * 初始化咨询列表
     * @param articleList
     */
    private void setUpArticleList(final List<ArticleBean> articleList){

        ArticleAdapter articleAdapter = new ArticleAdapter(mAct,articleList,false);
        articleAdapter.setOnItemClickListener(new ArticleAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
              //  Toast.makeText(mAct, "Click" + articleList.get(position).getTitle(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(mAct,ArticalDetailActivity.class);
                intent.putExtra("articalData",articleList.get(position));
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {
            }
        });
        rv_list_article.setAdapter(articleAdapter);
        rv_list_article.setLayoutManager(new LinearLayoutManager(mAct));
        rv_list_article.setItemAnimator(new DefaultItemAnimator());
        rv_list_article.addItemDecoration(new ItemDivider().setDividerWith(8).setDividerColor(Color.TRANSPARENT));
    }

    @Override
    public void refreshHomePage(HomePageData homePageData) {
        if(homePageData!=null){
            setUpArticleList(homePageData.getArticles());
            setUpViewPager(homePageData.getCarousels());
            setUpMessage(homePageData.getMessages());
        }
    }

    private void setUpMessage(List<MessageBean> messages) {
        String content="";
        for(MessageBean e:messages){
            content+=e.getContent();
        }
        tv_news_message.setText(content);
    }

}
